package org.dragonnova.lamp;

import android.os.Handler;
import android.support.annotation.NonNull;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * Created by hucn on 2016/10/25.
 * Description:
 */
public class defaultDelivery implements MessageDelivery {

    private Executor executor;
    private LampListener lampListener;
    private TapListener tapListener;

    public defaultDelivery(Executor executor) {
        this.executor = executor;
    }

    public void setLampListener(LampListener listener) {
        lampListener = listener;
    }

    @Override
    public void setTapListener(TapListener listener) {
        tapListener = listener;
    }

    public defaultDelivery(final Handler handler) {
        // Make an Executor that just wraps the handler.
        executor = new Executor() {
            @Override
            public void execute(@NonNull Runnable command) {
                handler.post(command);
            }
        };
    }

    @Override
    public void postLampResponse(List<Lamp> lamps) {
        executor.execute(new LampsRunnable(lamps, null));
    }

    @Override
    public void postTapResponse(List<Tap> taps) {
        executor.execute(new TapsRunnable(taps, null));
    }

    @Override
    public void postLampError(ErrorCode error) {
        executor.execute(new LampsRunnable(null, error));
    }

    @Override
    public void postTapError(ErrorCode error) {
        executor.execute(new TapsRunnable(null, error));
    }


    private class LampsRunnable implements Runnable {
        private List<Lamp> lamps;
        private ErrorCode error;

        LampsRunnable(List<Lamp> lamps, ErrorCode error) {
            this.lamps = lamps;
            this.error = error;
        }

        @Override
        public void run() {
            if (error == null) {
                if (lampListener != null) {
                    lampListener.onRefresh(lamps);
                }
            } else {
                if (lampListener != null) {
                    lampListener.onError(error);
                }
            }
        }
    }

    private class TapsRunnable implements Runnable {
        private List<Tap> taps;
        private ErrorCode error;

        TapsRunnable(List<Tap> taps, ErrorCode error) {
            this.taps = taps;
            this.error = error;
        }

        @Override
        public void run() {
            if (error == null) {
                if (tapListener != null) {
                    tapListener.onRefresh(taps);
                }
            } else {
                if (tapListener != null) {
                    tapListener.onError(error);
                }
            }
        }
    }
}
